﻿
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<h3 class="center" id="headline"><a href="http://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html" target="_blank">Web Speech API</a> Demonstration</h3>
<div class="command-container">
    <b>Try below commands:</b>
    <ul>
        <li>copy</li>
        <li>clear</li>
        <li>reset</li>
        <li>open google</li>
        <li>search</li>
        <li>open map</li>
        <li>get direction</li>
        <li>get weather</li>
    </ul>
</div>
<div id="info">
  <p id="info_start">Click on the microphone icon and begin speaking.</p>
  <p id="info_speak_now">Speak now.</p>
  <p id="info_no_speech">
      No speech was detected. You may need to adjust your <a href="//support.google.com/chrome/bin/answer.py?hl=en&amp;answer=1407892">microphone settings</a>.
  </p>
  <p id="info_no_microphone" style="display:none">
    No microphone was found. Ensure that a microphone is installed and that <a href="//support.google.com/chrome/bin/answer.py?hl=en&amp;answer=1407892">microphone settings</a> are configured correctly.</p>
  <p id="info_allow">Click the "Allow" button above to enable your microphone.</p>
  <p id="info_denied">Permission to use microphone was denied.</p>
  <p id="info_blocked">Permission to use microphone is blocked. To change,
    go to chrome://settings/contentExceptions#media-stream</p>
  <p id="info_upgrade">Web Speech API is not supported by this browser.
     Upgrade to <a href="//www.google.com/chrome">Chrome</a>
     version 25 or later.</p>
</div>
<div class="right">
    <button id="start_button" >
    <img id="start_img" src="@Url.Content("~/Content/img/mic.gif")" alt="Start"></button>
</div>
<div id="results">
  <span id="final_span" class="final"></span>
  <span id="interim_span" class="interim"></span>
  <p>
</div>
<div class="center">
  <div class="sidebyside" style="text-align:right">
    <button id="copy_button" class="button" data-clipboard-target="#final_span">Copy</button>
    <div id="copy_info" class="info">
      Press Control-C to copy text.<br>(Command-C on Mac.)
    </div>
  </div>
  <div class="sidebyside">
    <button id="clear_button" class="button">Clear</button> 
  </div> 
  <div class="sidebyside">
    <button id="stop_button" class="button">Reset</button> 
  </div> 
  <div id="div_language">
    <select id="select_language"></select>
    &nbsp;&nbsp;
    <select id="select_dialect"></select>
  </div>

   <p class="copy-to-head">Copy to</p>
   <div class="copy-to"></div>
</div>

@section script{
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<script>
    $(function () { 
        var langs =
[['Afrikaans', ['af-ZA']],
 ['Bahasa Indonesia', ['id-ID']],
 ['Bahasa Melayu', ['ms-MY']],
 ['Català', ['ca-ES']],
 ['Čeština', ['cs-CZ']],
 ['Deutsch', ['de-DE']],
 ['English', ['en-AU', 'Australia'],
                     ['en-CA', 'Canada'],
                     ['en-IN', 'India'],
                     ['en-NZ', 'New Zealand'],
                     ['en-ZA', 'South Africa'],
                     ['en-GB', 'United Kingdom'],
                     ['en-US', 'United States']],
 ['Español', ['es-AR', 'Argentina'],
                     ['es-BO', 'Bolivia'],
                     ['es-CL', 'Chile'],
                     ['es-CO', 'Colombia'],
                     ['es-CR', 'Costa Rica'],
                     ['es-EC', 'Ecuador'],
                     ['es-SV', 'El Salvador'],
                     ['es-ES', 'España'],
                     ['es-US', 'Estados Unidos'],
                     ['es-GT', 'Guatemala'],
                     ['es-HN', 'Honduras'],
                     ['es-MX', 'México'],
                     ['es-NI', 'Nicaragua'],
                     ['es-PA', 'Panamá'],
                     ['es-PY', 'Paraguay'],
                     ['es-PE', 'Perú'],
                     ['es-PR', 'Puerto Rico'],
                     ['es-DO', 'República Dominicana'],
                     ['es-UY', 'Uruguay'],
                     ['es-VE', 'Venezuela']],
 ['Euskara', ['eu-ES']],
 ['Français', ['fr-FR']],
 ['Galego', ['gl-ES']],
 ['Hrvatski', ['hr_HR']],
 ['IsiZulu', ['zu-ZA']],
 ['Íslenska', ['is-IS']],
 ['Italiano', ['it-IT', 'Italia'],
                     ['it-CH', 'Svizzera']],
 ['Magyar', ['hu-HU']],
 ['Nederlands', ['nl-NL']],
 ['Norsk bokmål', ['nb-NO']],
 ['Polski', ['pl-PL']],
 ['Português', ['pt-BR', 'Brasil'],
                     ['pt-PT', 'Portugal']],
 ['Română', ['ro-RO']],
 ['Slovenčina', ['sk-SK']],
 ['Suomi', ['fi-FI']],
 ['Svenska', ['sv-SE']],
 ['Türkçe', ['tr-TR']],
 ['български', ['bg-BG']],
 ['Pусский', ['ru-RU']],
 ['Српски', ['sr-RS']],
 ['한국어', ['ko-KR']],
 ['中文', ['cmn-Hans-CN', '普通话 (中国大陆)'],
                     ['cmn-Hans-HK', '普通话 (香港)'],
                     ['cmn-Hant-TW', '中文 (台灣)'],
                     ['yue-Hant-HK', '粵語 (香港)']],
 ['日本語', ['ja-JP']],
 ['Lingua latīna', ['la']]];

        for (var i = 0; i < langs.length; i++) {
            $("#select_language").append($("<option/>").val(langs[i][0]).text(langs[i][0]));
        }
        $("#select_language").change(function () {
            $("#select_dialect").html("");
            var list = langs[$("#select_language")[0].selectedIndex];
            for (var i = 1; i < list.length; i++) {
                $("#select_dialect").append($("<option/>").val(list[i][0]).text(list[i][1]));
            }
            if (list[1].length == 1)
                $("#select_dialect").hide();
            else
                $("#select_dialect").show();
            if (recognizing) {
                recognizing = false;
                recognition.stop();
            }
        });
        $("#select_language").val("English");
        $("#select_language").change();
        $("#select_dialect").val("en-US");
        $("#select_dialect").change(function () {
            if (recognizing) {
                recognizing = false;
                recognition.stop();
            }
        });

        showInfo('info_start'); 
        var final_transcript = '';
        var recognizing = false;
        var ignore_onend;
        var start_timestamp;
        if (!('webkitSpeechRecognition' in window)) {
            $("#start_button").hide();
            showInfo('info_upgrade');
        } else {
            $("#start_button").show();
            var recognition = new webkitSpeechRecognition();
            recognition.continuous = true;
            recognition.interimResults = true;
            recognition.onstart = function () {
                recognizing = true;
                showInfo('info_speak_now');
                start_img.src = 'Content/img/mic-animate.gif'; 
            };
            recognition.onerror = function (event) {
                if (event.error == 'no-speech') {
                    start_img.src = 'Content/img/mic.gif';
                    showInfo('info_no_speech');
                    ignore_onend = true;
                }
                if (event.error == 'audio-capture') {
                    start_img.src = 'Content/img/mic.gif';
                    showInfo('info_no_microphone');
                    ignore_onend = true;
                }
                if (event.error == 'not-allowed') {
                    if (event.timeStamp - start_timestamp < 100) {
                        showInfo('info_blocked');
                    } else {
                        showInfo('info_denied');
                    }
                    ignore_onend = true;
                }
            };
            recognition.onend = function () { 
                recognizing = false;
                if (ignore_onend) {
                    return;
                }
                start_img.src = 'Content/img/mic.gif';
                if (!final_transcript) {
                    showInfo('info_start');
                    return;
                }
                showInfo('');
                if (window.getSelection) {
                    window.getSelection().removeAllRanges();
                    var range = document.createRange();
                    range.selectNode(document.getElementById('final_span'));
                    window.getSelection().addRange(range);
                } 
            };
            recognition.onresult = function (event) { 
                var interim_transcript = '';
                var isCommand = false;
                for (var i = event.resultIndex; i < event.results.length; ++i) {
                    var transcript = event.results[i][0].transcript;
                    if (transcript && event.results[i].isFinal) {
                        var lowerCaseTranscript = $.trim(transcript.toLowerCase()); 
                        switch (lowerCaseTranscript) {
                            case "copy":
                                isCommand = true;
                                $("#copy_button").click();
                                responsiveVoice.speak($("#final_span").text() + " has been copied.");
                                break;
                            case "clear":
                                isCommand = true;
                                $("#clear_button").click();
                                responsiveVoice.speak("Cleared successful.");
                                break;
                            case "reset":
                                isCommand = true;
                                $("#stop_button").click();
                                responsiveVoice.speak("Reset successful.");
                                break;
                            case "search":
                                isCommand = true;
                                if ($("#final_span").text() == "") {
                                    responsiveVoice.speak("Please speak the search term first.");
                                } else {
                                    window.open("https://www.google.com/?gws_rd=ssl#q=" + $("#final_span").text(), "_blank");
                                    responsiveVoice.speak("Google search has been opened in another window.");
                                }
                                break;
                            case "open google":
                                isCommand = true;
                                window.open("http://www.google.com", "_blank")
                                responsiveVoice.speak("http://www.google.com has been opened in another window.");
                                break;
                            case "open map":
                                isCommand = true;
                                if ($("#final_span").text() == "") {
                                    responsiveVoice.speak("Please speak the place first.");
                                } else {
                                    window.open("https://www.google.com/maps/place/" + $("#final_span").text(), "_blank")
                                    responsiveVoice.speak("Google map has been opened in another window.");
                                }
                                break;
                            case "get direction":
                                isCommand = true;
                                if ($("#final_span").text() == "") {
                                    responsiveVoice.speak("Please speak the destination first.");
                                } else {
                                    window.open("https://www.google.com/maps/dir/Current+Location/" + $("#final_span").text(), "_blank")
                                    responsiveVoice.speak("Google map has been opened in another window.");
                                }
                                break;
                            case "get weather":
                                isCommand = true;
                                window.open("https://www.yahoo.com/news/weather/", "_blank")
                                responsiveVoice.speak("Yahoo Weather has been opened in another window.");
                                break;
                        } 
                    } 
                    if (isCommand) {
                        return;
                    } else {
                        if (event.results[i].isFinal) {
                            final_transcript += transcript;
                        } else {
                            interim_transcript += transcript;
                        }
                    } 
                }
                if (!isCommand) {
                    final_transcript = capitalize(final_transcript);
                    final_span.innerHTML = linebreak(final_transcript);
                    interim_span.innerHTML = linebreak(interim_transcript);
                    if (final_transcript || interim_transcript) {
                        showButtons('inline-block');
                    }
                }
            };
        }

        var two_line = /\n\n/g;
        var one_line = /\n/g;
        function linebreak(s) {
            return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
        }
        var first_char = /\S/;
        function capitalize(s) {
            return s.replace(first_char, function (m) { return m.toUpperCase(); });
        }
        function createEmail() {
            var n = final_transcript.indexOf('\n');
            if (n < 0 || n >= 80) {
                n = 40 + final_transcript.substring(40).indexOf(' ');
            }
            var subject = encodeURI(final_transcript.substring(0, n));
            var body = encodeURI(final_transcript.substring(n + 1));
            window.location.href = 'mailto:?subject=' + subject + '&body=' + body;
        }
        $("#copy_button").click(function (e) {
            //if (recognizing) {
                //recognizing = false;
                //recognition.stop();
            //} 
            $(".copy-to").text($("#final_span").text()); 
        });
        $("#clear_button").click(function () {
            $(".copy-to").text("");
            $("#final_span").text("");
            $("#interim_span").text("");
        });
        $("#stop_button").click(function () {
            if (recognizing) {
                recognizing = false;
                recognition.stop();
            }           
            $(".copy-to").text("");
            $("#final_span").text("");
            $("#interim_span").text("");
        });
        $("#start_button").click(function (event) {
            if (recognizing) {
                recognition.stop();
                return;
            }
            final_transcript = '';
            recognition.lang = select_dialect.value;
            recognition.start();
            ignore_onend = false;
            final_span.innerHTML = '';
            interim_span.innerHTML = '';
            start_img.src = 'Content/img/mic-slash.gif';
            showInfo('info_allow');
            showButtons('none');
            start_timestamp = event.timeStamp;
        });
        function showInfo(s) {
            if (s) {
                for (var child = info.firstChild; child; child = child.nextSibling) {
                    if (child.style) {
                        child.style.display = child.id == s ? 'inline' : 'none';
                        if (child.id == s) {
                            responsiveVoice.speak($(child).text());
                        }
                    }
                }
                info.style.visibility = 'visible';
            } else {
                info.style.visibility = 'hidden';
            }
        }
        var current_style;
        function showButtons(style) {
            if (style == current_style) {
                return;
            }
            current_style = style;
            //copy_button.style.display = style;
            //email_button.style.display = style;
            //copy_info.style.display = 'none';
            //email_info.style.display = 'none';
        }
        setTimeout(function () {
            responsiveVoice.speak("Welcome to use Web Speech API demonstration website!");
            responsiveVoice.speak($("#info_start").text());
        }, 1000);
    })
</script>
}
